<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>观看页面</title>
</head>
<body>
<h2>👀 观看中...</h2>
<video id="remoteVideo" autoplay playsinline controls></video>

<script>
    const room = new URLSearchParams(location.search).get("room") || "default";
    const ws = new WebSocket(`ws://${location.host}/ws/subscribe?room=${room}`);
    const pc = new RTCPeerConnection({
        iceServers: [{ urls: "stun:127.0.0.1:3478" }]
    });

    const remoteVideo = document.getElementById("remoteVideo");
    let remoteDescSet = false;
    const pendingCandidates = [];

    pc.ontrack = (event) => {
        if (remoteVideo.srcObject !== event.streams[0]) {
            remoteVideo.srcObject = event.streams[0];
        }
    };

    pc.onicecandidate = (event) => {
        if (event.candidate) {
            ws.send(JSON.stringify({ type: "candidate", candidate: event.candidate }));
        }
    };

    ws.onopen = async () => {
        const offer = await pc.createOffer();
        await pc.setLocalDescription(offer);
       setTimeout(()=>{
           ws.send(JSON.stringify({ type: "offer", sdp: offer.sdp }));
       },100)
    };

    ws.onmessage = async (msg) => {
        const data = JSON.parse(msg.data);

        if (data.type === "answer") {
            await pc.setRemoteDescription({ type: "answer", sdp: data.sdp });
            remoteDescSet = true;
            pendingCandidates.forEach(candidate => pc.addIceCandidate(candidate));
        } else if (data.type === "candidate") {
            if (remoteDescSet) {
                await pc.addIceCandidate(data.candidate);
            } else {
                pendingCandidates.push(data.candidate);
            }
        }
    };

</script>
</body>
</html>
